package com.ponhu.ea2.goodsCenter.bms.api.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.ponhu.ea2.common.basic.model.PagedResult;
import com.ponhu.ea2.common.basic.model.ResponseBean;
import com.ponhu.ea2.dto.InventoryCodeGenerateDto;
import com.ponhu.ea2.dto.InventoryMaintainCostDto;
import com.ponhu.ea2.dto.InventoryMaintainResultDto;
import com.ponhu.ea2.enums.FileTypeEnum;
import com.ponhu.ea2.enums.ThirdSystemEnum;
import com.ponhu.ea2.properties.GoodsProperties;
import com.ponhu.ea2.properties.UIProperties;
import com.ponhu.ea2.query.ApplyingQuery;
import com.ponhu.ea2.query.LiveGoodsInfoQuery;
import com.ponhu.ea2.service.facade.*;
import com.ponhu.ea2.support.exception.BusinessRuntimeException;
import com.ponhu.ea2.support.validation.annotions.ValidateEnumValue;
import com.ponhu.ea2.utils.QiNiuUploadUtils;
import com.ponhu.ea2.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Method;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.ws.rs.core.Context;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.List;

import static com.ponhu.ea2.enums.ResponseCodeEnum.PARAMETER_IS_INCORRECT_800001;

@Slf4j
@RestController
@RefreshScope
@RequestMapping("/common")
@Api(tags = "通用接口", value = "CommonController")
public class CommonController {

    @Value("${third-party.erp.realm-name}")
    private String realmName;
    @Value("${third-party.erp.appkey}")
    private String appkey;
    @Value("${third-party.erp.sign_type}")
    private String signType;
    @Value("${third-party.erp.channel}")
    private String channel;
    @Value("${third-party.ponhu.url}")
    private String url;

    @DubboReference(version = "1.0.0", check = false)
    private CommonApiService commonApiService;

    @DubboReference(version = "1.0.0", check = false, methods = {
            @Method(name = "aiPictureInventoryBatchSync", timeout = 1800000),
            @Method(name = "getAllInventorys", timeout = 1800000)
    })
    private InventoryApiService inventoryApiService;

    @DubboReference(version = "1.0.0", check = false, methods = {
            @Method(name = "aiPictureClassifyBatchSync", timeout = 1800000)
    })
    private PhMaterialInfoApiService phMaterialInfoApiService;

    @DubboReference(version = "1.0.0", check = false)
    SellingPointsService sellingPointsService;

    @DubboReference(version = "1.0.0", check = false)
    ApplyingStockDataService applyingStockDataService;

    @DubboReference(version = "1.0.0", check = false)
    GoodsApiService goodsApiService;

    @Resource
    GoodsProperties goodsProperties;
    @Resource
    UIProperties uiProperties;


    /**
     * 判断货品编码是否已经使用并入库：true-已使用，false-未使用
     *
     * @return
     */
    @ApiOperation(value = "判断货品编码是否已经使用并入库：true-已使用，false-未使用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "inventoryCode", value = "货品编码",
                    dataType = "string", paramType = "query", required = true)
    })
    @GetMapping("/checkInventoryCodeIsUsed")
    public ResponseBean<Boolean> checkInventoryCodeIsUsed(@RequestParam String inventoryCode) {

        return ResponseBean.ok(inventoryApiService.checkInventoryCodeIsUsed(inventoryCode));
    }

    /**
     * 根据入库方式生成货品编码
     *
     * @return
     */
    @ApiOperation(value = "根据入库方式生成货品编码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "入库方式",
                    dataType = "string", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "生成编码数量",
                    dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "systemEnum",
                    value = "调用方标识：SYSTEM_CLOUD(云商系统)，SYSTEM_PURCHASE(采购系统)",
                    dataType = "string", paramType = "query", required = true),
            @ApiImplicitParam(name = "isSecondhand", value = "是否是二奢：1是，2否",
                    dataType = "int", paramType = "query", required = true)
    })
    @GetMapping("/getInventoryCodeByType")
    public ResponseBean<List<String>> getInventoryCodeByType(@RequestParam String type,
                                                             @RequestParam Integer size,
                                                             @RequestParam ThirdSystemEnum systemEnum,
                                                             @RequestParam Integer isSecondhand) {

        return ResponseBean.ok(inventoryApiService.getInventoryCodeByType(type, size, systemEnum, isSecondhand));
    }

    /**
     * 根据入库方式生成货品编码
     *
     * @return
     */
    @ApiOperation(value = "根据入库方式生成货品编码")
    @PostMapping("/generateInventoryCodeByType")
    public ResponseBean<List<String>> generateInventoryCodeByType(
            @RequestBody @Validated InventoryCodeGenerateDto generateDto) {

        ThirdSystemEnum systemEnum;
        try {
            systemEnum = ThirdSystemEnum.valueOf(generateDto.getSystemEnum());
        } catch (Exception e) {
            return ResponseBean.error(PARAMETER_IS_INCORRECT_800001.getCode(), "参数不正确：调用方标识错误");
        }

        return ResponseBean.ok(inventoryApiService.getInventoryCodeByType(
                generateDto.getType(), generateDto.getSize(), systemEnum, generateDto.getIsSecondhand()));
    }

    /**
     * 获取指定属性ID所属的全部属性值
     *
     * @return
     */
    @ApiOperation(value = "获取指定属性ID所属的全部属性值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "propId", value = "属性ID", dataType = "long", paramType = "query")
    })
    @GetMapping("/getAllPropValues")
    public ResponseBean<List<PhPropertyVo>> getAllPropValues(
            @RequestParam(value = "propId") Long propId) {

        return ResponseBean.ok(commonApiService.getAllPropValues(propId));
    }

    /**
     * 获取指定类目ID所属的全部材质属性
     *
     * @return
     */
    @ApiOperation(value = "获取指定类目ID所属的全部材质属性")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "类目ID", dataType = "long", paramType = "query")
    })
    @GetMapping("/getAllMaterialProps")
    public ResponseBean<List<PhPropertyVo>> getAllMaterialProps(
            @RequestParam(value = "categoryId") Long categoryId) {

        return ResponseBean.ok(commonApiService.getAllTypeProps(categoryId, "材质"));
    }

    /**
     * 获取指定类目ID所属的全部颜色属性
     *
     * @return
     */
    @ApiOperation(value = "获取指定类目ID所属的全部颜色属性")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "类目ID", dataType = "long", paramType = "query")
    })
    @GetMapping("/getAllColorProps")
    public ResponseBean<List<PhPropertyVo>> getAllColorProps(
            @RequestParam(value = "categoryId") Long categoryId) {

        return ResponseBean.ok(commonApiService.getAllTypeProps(categoryId, "颜色"));
    }

    /**
     * 获取指定类目ID所属的全部货品属性
     *
     * @return
     */
    @ApiOperation(value = "获取指定类目ID所属的全部货品属性")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "level", value = "类目层级：只能传1、2、3", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "类目ID", dataType = "long", paramType = "query")
    })
    @GetMapping("/getAllInventoryProps")
    public ResponseBean<List<PhPropertyEditVo>> getAllInventoryProps(
            @ValidateEnumValue(intValues = {1, 2, 3}, message = "类目层级只能传1/2/3")
            @RequestParam(value = "level") Integer level,
            @Valid @NotNull(message = "类目ID不可为空")
            @RequestParam(value = "categoryId") Long categoryId) {

        List<PhPropertyEditVo> allInventoryProps = commonApiService.getAllInventoryProps(level, categoryId);
        return ResponseBean.ok(allInventoryProps);
    }

    /**
     * 获取指定类目ID所属的全部属性
     *
     * @return
     */
    @ApiOperation(value = "获取指定类目ID所属的全部属性")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "level", value = "类目层级：只能传1、2、3", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "类目ID", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "属性类型:1物料属性，2货品属性，3商品属性", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/getAllProps")
    public ResponseBean<List<PhPropertyEditVo>> getAllProps(
            @ValidateEnumValue(intValues = {1, 2, 3}, message = "类目层级只能传1/2/3")
            @RequestParam(value = "level") Integer level,
            @Valid @NotNull(message = "类目ID不可为空")
            @RequestParam(value = "categoryId") Long categoryId,
            @ValidateEnumValue(intValues = {1, 2, 3}, message = "1物料属性，2货品属性，3商品属性")
            @RequestParam(value = "type") Integer type) {

        List<PhPropertyEditVo> allProps = commonApiService.getAllProps(level, categoryId, type);
        return ResponseBean.ok(allProps);
    }

    /**
     * 获取全部货品附件字段项
     *
     * @return
     */
    @ApiOperation(value = "获取全部货品附件字段项")
    @GetMapping("/getAllInventoryAnnexs")
    public ResponseBean<List<PhSysDictItemVo>> getAllInventoryAnnexs() {

        List<PhSysDictItemVo> allInventoryAnnexs = commonApiService.getAllInventoryAnnexs();
        return ResponseBean.ok(allInventoryAnnexs);
    }

    /**
     * 获取全部货品配件字段项
     *
     * @return
     */
    @ApiOperation(value = "获取全部货品配件字段项")
    @GetMapping("/getAllInventoryAccessorys")
    public ResponseBean<List<PhSysDictItemVo>> getAllInventoryAccessorys() {

        List<PhSysDictItemVo> allInventoryAccessorys = commonApiService.getAllInventoryAccessorys();
        return ResponseBean.ok(allInventoryAccessorys);
    }

    /**
     * 获取全部货品类型字段项
     *
     * @return
     */
    @ApiOperation(value = "获取全部货品类型字段项")
    @GetMapping("/getAllInventoryTypes")
    public ResponseBean<List<PhSysDictItemVo>> getAllInventoryTypes() {
        List<PhSysDictItemVo> allInventoryTypes = commonApiService.getAllInventoryTypes();
        return ResponseBean.ok(allInventoryTypes);
    }

    /**
     * 获取全部货品来源字段项
     *
     * @return
     */
    @ApiOperation(value = "获取全部货品来源字段项")
    @GetMapping("/getAllInventoryChannels")
    public ResponseBean<List<PhSysDictItemVo>> getAllInventoryChannels() {
        List<PhSysDictItemVo> allInventoryChannels = commonApiService.getAllInventoryChannels();
        return ResponseBean.ok(allInventoryChannels);
    }

    @ApiOperation(value = "获取全部入库方式")
    @GetMapping("/getAllWarehouseWays")
    public ResponseBean<List<PhSysDictItemVo>> getAllWarehouseWays() {
        List<PhSysDictItemVo> data = commonApiService.getAllWarehouseWays();
        return ResponseBean.ok(data);
    }

    /**
     * 获取全部成色类型字段项
     *
     * @return
     */
    @ApiOperation(value = "获取全部成色类型字段项")
    @GetMapping("/getAllConditionTypes")
    public ResponseBean<List<PhSysDictItemVo>> getAllConditionTypes() {
        List<PhSysDictItemVo> allInventoryChannels = commonApiService.getAllConditionTypes();
        return ResponseBean.ok(allInventoryChannels);
    }

    /**
     * 获取全部品牌或搜索品牌
     * 模糊匹配：品牌英文名称、品牌中文名称、别称
     *
     * @return
     */
    @ApiOperation(value = "获取全部品牌或搜索品牌")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "品牌英文名称或品牌中文名称或别称",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isAll", value = "是否需要全部数据：true-是，false-否(去除无效数据)",
                    dataType = "boolean", paramType = "query")
    })
    @GetMapping("/getPhBrandsByName")
    public ResponseBean<List<PhBrandVo>> getPhBrandsByName(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "isAll", required = false, defaultValue = "false") Boolean isAll) {

        return ResponseBean.ok(commonApiService.getPhBrandsByName(name, isAll));
    }

    /**
     * 根据系列查询所有型号
     *
     * @return
     */
    @ApiOperation(value = "根据系列查询所有型号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "seriesId", value = "系列ID", dataType = "long", paramType = "query")
    })
    @GetMapping("/getPhModelsBySeries")
    public ResponseBean<List<PhModelVo>> getPhModelsBySeries(
            @RequestParam(value = "seriesId", required = false) Long seriesId) {
        List<PhModelVo> phModelVos = commonApiService.getPhModelsBySeries(seriesId);
        return ResponseBean.ok(phModelVos);
    }

    /**
     * 根据品牌或系列查询所有物料型号
     *
     * @return
     */
    @ApiOperation(value = "根据品牌或系列查询所有物料型号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "brandId", value = "品牌ID", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "seriesId", value = "系列ID", dataType = "long", paramType = "query")
    })
    @GetMapping("/getPhMaterialModelsByBrandOrSeries")
    public ResponseBean<List<PhMaterialModelVo>> getPhMaterialModelsByBrandOrSeries(
            @RequestParam(value = "brandId", required = false) Long brandId,
            @RequestParam(value = "seriesId", required = false) Long seriesId) {

        List<PhMaterialModelVo> phModelVos = commonApiService
                .getPhMaterialModelsByBrandOrSeries(brandId, seriesId);
        return ResponseBean.ok(phModelVos);
    }

    /**
     * 获取指定分级和父级类目ID的全部类目集合
     *
     * @return
     */
    @ApiOperation(value = "获取指定分级和父级类目ID的全部类目集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "level", value = "要获取的类目分级：1-一级，2-二级，3-三级",
                    dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "parentId", value = "要获取类目的父级类目ID：0-一级类目父级类目ID",
                    dataType = "long", paramType = "query", required = true),
            @ApiImplicitParam(name = "isAll", value = "是否需要全部数据：true-是，false-否(去除无效数据)",
                    dataType = "boolean", paramType = "query")
    })
    @GetMapping("/getPhCategorysByLevel")
    public ResponseBean<List<PhCategoryVo>> getPhCategorysByLevel(
            @RequestParam(value = "level") Integer level,
            @RequestParam(value = "parentId") Long parentId,
            @RequestParam(value = "isAll", required = false, defaultValue = "false") Boolean isAll) {

        return ResponseBean.ok(commonApiService.getPhCategorysByLevel(level, parentId, isAll));
    }

    /**
     * 获取全部货源字段项
     *
     * @return
     */
    @ApiOperation(value = "获取全部货源字段项")
    @GetMapping("/getAllInventorySources")
    public ResponseBean<List<PhSysDictItemVo>> getAllInventorySources() {
        List<PhSysDictItemVo> allInventoryChannels = commonApiService.getAllInventorySources();
        return ResponseBean.ok(allInventoryChannels);
    }

    /**
     * 根据品牌查询系列
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "brandId", value = "品牌id",
                    dataType = "Long", paramType = "query", required = true)
    })
    @ApiOperation(value = "根据品牌获取系列信息")
    @GetMapping("/queryPhSeries")
    public ResponseBean<List<PhSeriesVO>> queryPhSeriesByBrandId(Long brandId) {

        return ResponseBean.ok(commonApiService.queryPhSeriesByBrandId(brandId));
    }

    /**
     * 根据多品牌品牌查询系列
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "brandIds", value = "品牌ID集合",
                    dataType = "int", allowMultiple = true, paramType = "query", required = true)
    })
    @ApiOperation(value = "根据多品牌品牌查询系列")
    @GetMapping("/queryPhSeriesByBrandIds")
    public ResponseBean<List<PhSeriesVO>> queryPhSeriesByBrandIds(
            @RequestParam(name = "brandIds") List<Long> brandIds) {

        return ResponseBean.ok(commonApiService.queryPhSeriesByBrandIds(brandIds));
    }

    /**
     * 根据品牌查询所有型号
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "brandId", value = "品牌id",
                    dataType = "Long", paramType = "query", required = true)
    })
    @ApiOperation(value = "根据品牌获取所有型号")
    @GetMapping("/queryPhModelByBrandId")
    public ResponseBean<List<PhModelVo>> queryPhModelByBrandId(Long brandId) {
        List<PhModelVo> list = commonApiService.queryPhModelByBrandId(brandId);
        return ResponseBean.ok(list);
    }

    /**
     * 根据多品牌查询所有型号
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "brandIds", value = "品牌ID集合",
                    dataType = "int", allowMultiple = true, paramType = "query", required = true)
    })
    @ApiOperation(value = "根据多品牌查询所有型号")
    @GetMapping("/queryPhModelByBrandIds")
    public ResponseBean<List<PhModelVo>> queryPhModelByBrandIds(
            @RequestParam(name = "brandIds") List<Long> brandIds) {

        return ResponseBean.ok(commonApiService.queryPhModelByBrandIds(brandIds));
    }

    /**
     * 获取全部国家信息
     *
     * @return
     */
    @ApiOperation(value = "获取全部国家信息")
    @GetMapping("/getAllCountries")
    public ResponseBean<List<String>> getAllCountries() {
        List<String> allCountries = commonApiService.getAllCountries();
        return ResponseBean.ok(allCountries);
    }

    /**
     * 获取全部国家信息-返回对象信息
     *
     * @return
     */
    @ApiOperation(value = "获取全部国家信息-返回对象信息")
    @GetMapping("/getCountries")
    public ResponseBean<List<PhCountriesVo>> getCountries() {
        List<PhCountriesVo> allCountries = commonApiService.getAllCountriesForVo();
        return ResponseBean.ok(allCountries);
    }

    /**
     * 获取全部鉴定师信息
     *
     * @return
     */
    @ApiOperation(value = "获取全部鉴定师信息")
    @GetMapping("/getAllaccessories")
    public ResponseBean<List<PhAppraisalVo>> getAllaccessories() {
        // 设置请求方式
        log.info("鉴定师接口地址为：{}", url);
        try {
            String reslut = new RestTemplate().postForObject(url, null, String.class);
            String resultData = JSON.parseObject(reslut).getString("list");
            List<PhAppraisalVo> phAppraisalVos = Lists.newArrayList();
            if (StringUtils.isNotBlank(resultData)) {
                phAppraisalVos = JSON.parseArray(resultData, PhAppraisalVo.class);
            }
            return ResponseBean.ok(phAppraisalVos);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取胖总管鉴定师数据异常:{}", e);
        }
        return ResponseBean.ok();
    }

    /**
     * 按货品编码更新卖点音频
     *
     * @param inventoryCode
     * @return
     */
    @ApiOperation(value = "按货品编码更新卖点音频")
    @ApiImplicitParam(name = "inventoryCode", value = "货品编码",
            dataType = "String", paramType = "query", required = true)
    @GetMapping("/updateSellingPointsAudioByInventoryCode")
    public ResponseBean updateSellingPointsAudioByInventoryCode(@NotNull String inventoryCode) {
        boolean updateFlag = sellingPointsService.updateSellingPointsAudioByInventoryCode(inventoryCode);
        if (updateFlag) {
            return ResponseBean.ok("更新成功");
        }
        return ResponseBean.error("更新失败");
    }

    /**
     * 根据品类Id获取品类信息
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "品类id",
                    dataType = "Long", paramType = "query", required = true)
    })
    @ApiOperation(value = "根据品类Id获取品类信息")
    @GetMapping("/getCategoryByCategoryId")
    public ResponseBean<PhCategoryVo> getCategoryByCategoryId(Long categoryId) {
        return ResponseBean.ok(commonApiService.getCategoryByCategoryId(categoryId));
    }

    @ApiOperation(value = "获取全部采购类型")
    @GetMapping("/getAllPurchaseTypes")
    public ResponseBean<List<PhSysDictItemVo>> getAllPurchaseTypes() {
        List<PhSysDictItemVo> data = commonApiService.getAllPurchaseTypes();
        return ResponseBean.ok(data);
    }

    /*@ApiOperation(value = "获取全部采购渠道")
    @GetMapping("/getAllPurchaseChannel")
    public ResponseBean<List<PhSysDictItemVo>> getAllPurchaseChannel() {
        List<PhSysDictItemVo> data = commonApiService.getAllPurchaseChannel();
        return ResponseBean.ok(data);
    }*/

    /**
     * 上传图片到七牛云
     *
     * @param file
     * @return
     */
    @ApiOperation("上传图片")
    @PostMapping("/uploadImage")
    public ResponseBean uploadImage(@RequestParam("file") MultipartFile file) {
        if (file == null && file.isEmpty()) {
            return ResponseBean.error("图片不能为空");
        }
        final String originalFileName = file.getOriginalFilename();
        final String suffix = originalFileName.substring(originalFileName.lastIndexOf(".")).toLowerCase();
        if (!QiNiuUploadUtils.IMAGE_EXTENSIONS.contains(suffix)) {
            return ResponseBean.error("图片格式错误！");
        }
        try {
            if (file.getSize() >= goodsProperties.getUploadImageSize().toBytes()) {
                return ResponseBean.error(goodsProperties.getUploadImageTips());
            }
            return ResponseBean.ok(QiNiuUploadUtils.uploadPicture(file));
        } catch (Exception e) {
            log.error("图片上传失败：{}", e);
            return ResponseBean.error("图片上传失败，请稍后再试");
        }
    }

    /**
     * 上传图片到七牛云
     *
     * @param multipartFile
     * @return
     */
    @ApiOperation("上传文件")
    @PostMapping("/uploadFile")
    public ResponseBean uploadFile(@RequestParam("file") MultipartFile multipartFile) {
        if (multipartFile == null && multipartFile.isEmpty()) {
            return ResponseBean.error("文件不能为空");
        }
        String fileUrl = "";
        try {
            File file = QiNiuUploadUtils.MultipartFileToFile(multipartFile);
            fileUrl = QiNiuUploadUtils.uploadFile(file, FileTypeEnum.FILE);
            if (file.exists()) {
                if (file.delete()) {
                    log.info("临时文件删除成功");
                }
                ;
            }
            return ResponseBean.ok(fileUrl);
        } catch (Exception e) {
            log.error("文件上传失败：{}", e);
            return ResponseBean.error("文件上传失败，请稍后再试");
        }
    }

    /**
     * 获取条形码
     *
     * @param code
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "货品编码",
                    dataType = "String", required = true)
    })
    @ApiOperation("生成条形码")
    @GetMapping("/generateBarCode")
    public ResponseBean generateBarCode(@RequestParam(value = "code") String code) {
        return ResponseBean.ok(inventoryApiService.getBarCode(code));
    }

    /**
     * Erp养护增加货品相关成本
     *
     * @return
     */
    @ApiOperation(value = "Erp养护增加货品相关成本")
    @PostMapping("/inventoryMaintainCost")
    public ResponseBean<Boolean> inventoryMaintainCost(
            @RequestBody @Validated InventoryMaintainCostDto inventoryMaintainCostDto) {

        return ResponseBean.ok(inventoryApiService.inventoryMaintainCost(inventoryMaintainCostDto));
    }

    /**
     * Erp养护结果
     *
     * @return
     */
    @ApiOperation(value = "Erp养护结果")
    @PostMapping("/inventoryMaintainResult")
    public ResponseBean<Boolean> inventoryMaintainResult(
            @RequestBody @Validated InventoryMaintainResultDto inventoryMaintainResultDto) {
        Boolean result = inventoryApiService.inventoryMaintainResult(inventoryMaintainResultDto);
        return BooleanUtils.isTrue(result)?ResponseBean.ok():ResponseBean.error();
    }

    @ApiOperation(value = "直播查询商品详情")
    @PostMapping("/getGoodsInfoForLive")
    public ResponseBean<PagedResult<PhGoodsInfoForLiveVo>> getGoodsInfoForLive(
            @RequestBody @Validated LiveGoodsInfoQuery liveGoodsInfoQuery) {
        PagedResult<PhGoodsInfoForLiveVo> list = inventoryApiService.queryPhGoodsInfoForLiveVo(liveGoodsInfoQuery);
        return ResponseBean.ok(list);
    }

    /**
     * 查询调拨在途数据查询
     *
     * @param query
     * @return
     */
    @ApiOperation(value = "调拨在途数据查询")
    @PostMapping("/getApplyingStockData")
    public ResponseBean<PagedResult<ApplyingStockDataVo>> getApplyingStockData(@RequestBody @Validated ApplyingQuery query) {
        if (StringUtils.isNotBlank(query.getApplyStartTime())
                && StringUtils.isNotBlank(query.getApplyEndTime())) {
            // 校验查询时间是否大于3天
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDate startTime = LocalDate.parse(query.getApplyStartTime(), dateTimeFormatter);
            LocalDate endTime = LocalDate.parse(query.getApplyEndTime(), dateTimeFormatter);
            int days = Period.between(startTime, endTime).getDays();
            if (days > 3) {
                return ResponseBean.error("查询时间不能大于3天");
            }
        }
        return ResponseBean.ok(applyingStockDataService.getApplyingStockData(query));
    }

    /**
     * 导入物料编码批量包小检AI识图 - 同步
     *
     * @param uploadFile
     * @param response
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "导入物料编码批量包小检AI识图")
    @PostMapping("/aiPictureClassifyBatch/sync")
    public ResponseBean aiPictureClassifyBatchSync(@RequestBody MultipartFile uploadFile,
                                                   HttpServletResponse response) throws IOException {
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        try {
            Reader reader = new InputStreamReader(uploadFile.getInputStream());
            bufferedReader = new BufferedReader(reader);
            List<String> materialCodeList = Lists.newArrayList();
            String materialCode;
            while ((materialCode = bufferedReader.readLine()) != null) {
                if (StringUtils.isNotEmpty(materialCode))
                    materialCodeList.add(materialCode.trim());
            }

            if (CollectionUtils.isEmpty(materialCodeList))
                throw new BusinessRuntimeException(PARAMETER_IS_INCORRECT_800001);

            materialCodeList = phMaterialInfoApiService.aiPictureClassifyBatchSync(materialCodeList);

            if (CollectionUtils.isEmpty(materialCodeList)) return ResponseBean.ok();

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            String fileName = URLEncoder.encode("包小检AI识图失败物料编码列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".txt");

            Writer writer = new OutputStreamWriter(response.getOutputStream());
            bufferedWriter = new BufferedWriter(writer);
            Iterator<String> iterator = materialCodeList.iterator();
            while (iterator.hasNext()) {
                bufferedWriter.write(iterator.next());
                bufferedWriter.newLine();
            }
            return null;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 导入物料编码批量包小检AI识图 - 异步
     *
     * @param uploadFile
     */
    @ApiOperation(value = "导入物料编码批量包小检AI识图")
    @PostMapping("/aiPictureClassifyBatch/async")
    public ResponseBean aiPictureClassifyBatchAsync(@RequestBody MultipartFile uploadFile) throws IOException {
        BufferedReader bufferedReader = null;
        try {
            Reader reader = new InputStreamReader(uploadFile.getInputStream());
            bufferedReader = new BufferedReader(reader);
            List<String> materialCodeList = Lists.newArrayList();
            String materialCode;
            while ((materialCode = bufferedReader.readLine()) != null) {
                if (StringUtils.isNotEmpty(materialCode))
                    materialCodeList.add(materialCode.trim());
            }

            if (CollectionUtils.isEmpty(materialCodeList))
                throw new BusinessRuntimeException(PARAMETER_IS_INCORRECT_800001);

            return ResponseBean.ok(phMaterialInfoApiService.aiPictureClassifyBatchSync(materialCodeList));
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 导入货品编码批量包小检AI识图 - 同步
     *
     * @param uploadFile
     * @param response
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "导入货品编码批量包小检AI识图")
    @PostMapping("/aiPictureInventoryBatch/sync")
    public ResponseBean aiPictureInventoryBatchSync(@RequestBody MultipartFile uploadFile,
                                                    HttpServletResponse response) throws IOException {
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        try {
            Reader reader = new InputStreamReader(uploadFile.getInputStream());
            bufferedReader = new BufferedReader(reader);
            List<String> inventoryCodeList = Lists.newArrayList();
            String inventoryCode;
            while ((inventoryCode = bufferedReader.readLine()) != null) {
                if (StringUtils.isNotEmpty(inventoryCode))
                    inventoryCodeList.add(inventoryCode.trim());
            }

            if (CollectionUtils.isEmpty(inventoryCodeList))
                throw new BusinessRuntimeException(PARAMETER_IS_INCORRECT_800001);

            inventoryCodeList = inventoryApiService.aiPictureInventoryBatchSync(inventoryCodeList);

            if (CollectionUtils.isEmpty(inventoryCodeList)) return ResponseBean.ok();

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            String fileName = URLEncoder.encode("包小检AI识图失败货品编码列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".txt");

            Writer writer = new OutputStreamWriter(response.getOutputStream());
            bufferedWriter = new BufferedWriter(writer);
            Iterator<String> iterator = inventoryCodeList.iterator();
            while (iterator.hasNext()) {
                bufferedWriter.write(iterator.next());
                bufferedWriter.newLine();
            }

            return null;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 导入货品编码批量包小检AI识图 - 异步
     *
     * @param uploadFile
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "导入货品编码批量包小检AI识图")
    @PostMapping("/aiPictureInventoryBatch/async")
    public ResponseBean aiPictureInventoryBatchAsync(@RequestBody MultipartFile uploadFile) throws IOException {
        BufferedReader bufferedReader = null;
        try {
            Reader reader = new InputStreamReader(uploadFile.getInputStream());
            bufferedReader = new BufferedReader(reader);
            List<String> inventoryCodeList = Lists.newArrayList();
            String inventoryCode;
            while ((inventoryCode = bufferedReader.readLine()) != null) {
                if (StringUtils.isNotEmpty(inventoryCode))
                    inventoryCodeList.add(inventoryCode.trim());
            }

            if (CollectionUtils.isEmpty(inventoryCodeList))
                throw new BusinessRuntimeException(PARAMETER_IS_INCORRECT_800001);

            return ResponseBean.ok(inventoryApiService.aiPictureInventoryBatchAsync(inventoryCodeList));
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取前端配置信息
     *
     * @return
     */
    @ApiOperation(value = "获取前端配置信息")
    @GetMapping("/getConfigs")
    public ResponseBean getConfigs() {
        return ResponseBean.ok(uiProperties);
    }


    /**
     * 根据货品编码获取商品详情
     *
     * @param code
     * @return
     */
    @ApiOperation(value = "根据货品编码获取商品详情")
    @GetMapping("/getGoodsInfo")
    public ResponseBean<GoodsInfoForErpVo> getGoodsInfo(@NotBlank @RequestParam(value = "code") String code) {
        GoodsInfoForErpVo goodsInfo = new GoodsInfoForErpVo();
        if (StringUtils.isNotBlank(code)) {
            goodsInfo = goodsApiService.getGoodsInfoForErp(code);
        }
        return ResponseBean.ok(goodsInfo);
    }

    /**
     * 根据货品编码获取商品详情
     *
     * @return
     */
    @ApiOperation(value = "下载货品信息接口")
    @GetMapping("/exportExcelForInventory")
    public ResponseBean exportExcelForInventory(@Context HttpServletResponse response) {
        String url = inventoryApiService.getAllInventorys();
        return ResponseBean.ok(url);
    }

    /**
     * 会员小程序根据货品编码获取货品信息接口
     * @param inventoryCodes
     * @return
     */
    @ApiOperation(value = "会员小程序根据货品编码获取货品信息接口")
    @GetMapping("/queryGoodsinfoForApplet")
    public ResponseBean<List<PhInventoryToAmqpVo>> queryGoodsinfoForApplet(
            @NotBlank @RequestParam(value = "inventoryCodes") List<String> inventoryCodes){
        return ResponseBean.ok(inventoryApiService.queryGoodsinfoForApplet(inventoryCodes));
    }
}